#include <sys/ipc.h>
#include <sys/sem.h>
#include "semaphores.h"

	Semaphore::Semaphore(int initval)
	{
		key_t key = ftok("./semaphores.h", next_ipc_id_token++);
		id = semget(key, 1, IPC_CREAT | 0660);
		semctl(id, 0, SETVAL, initval);
	}

	Semaphore::~Semaphore()
	{
		semctl(id, 0, IPC_RMID, 0);
	}

	int Semaphore::P()
	{
		struct sembuf buf;
		buf.sem_num = 0;
		buf.sem_op = -1;
		buf.sem_flg = 0;
		return semop(id, &buf, 1);
	}

	int Semaphore::V()
	{
		struct sembuf buf;
		buf.sem_num = 0;
		buf.sem_op = 1;
		buf.sem_flg = 0;
		return semop(id, &buf, 1);
	}

        char Semaphore::next_ipc_id_token = 0;


